using System;
using System.Collections.Generic;
using System.Threading;

namespace Clandestine.Audio
{
	internal class StreamingThread
	{
		private List<StreamingBuffer> streamingBuffers = new List<StreamingBuffer>();
		private Thread thread = null;
		private Audio audio;
		
		public StreamingThread(Audio audio)
		{
			this.audio = audio;
		}
		
		internal void AddPollee(StreamingBuffer isd)
		{
			lock (streamingBuffers)
			{
				streamingBuffers.Add(isd);
				
				if (thread == null)
				{
					thread = new Thread(new ThreadStart(threadProc));
					thread.Start();
				}
			}
		}
		
		internal void RemovePollee(StreamingBuffer isd)
		{
			lock (streamingBuffers)
			{
				streamingBuffers.Remove(isd);
			}
		}
		
		private void threadProc()
		{
			List<StreamingBuffer> toRemove = new List<StreamingBuffer>();
			
			while (true)
			{
				audio.LockALAndMakeActive();
				
				lock (streamingBuffers)
				{
					if (streamingBuffers.Count == 0)
					{
						thread = null;
						return;
					}
					
					foreach (StreamingBuffer isd in streamingBuffers)
						if (!isd.Poll())
							toRemove.Add(isd);
					
					foreach (StreamingBuffer risd in toRemove)
						streamingBuffers.Remove(risd);
					
					toRemove.Clear();
				}
				
				audio.UnlockAL();
				
				Thread.Sleep(50);
			}
		}
	}
}
